package pers.qianyu.auth.utils;

import io.jsonwebtoken.*;
import org.springframework.security.core.*;
import org.springframework.security.core.userdetails.*;
import pers.qianyu.auth.constants.*;

import java.util.*;
import java.util.stream.*;

/**
 * JWT 工具类
 */
public class JwtTokenUtils {

    /**
     * 生成令牌
     *
     * @param authentication 用户
     * @return 令牌
     */
    public static String generateToken(Authentication authentication) {
        Map<String, Object> claims = new HashMap<>(3);
        String username = null;
        if (authentication != null) {
            Object principal = authentication.getPrincipal();
            if (principal instanceof UserDetails) {
                username = ((UserDetails) principal).getUsername();
            }
        }
        claims.put(JwtConstants.CREATED, new Date());
        claims.put(JwtConstants.AUTHORITIES,
                Optional.ofNullable(authentication.getAuthorities())
                        .map(Collection::stream)
                        .orElseGet(Stream::empty)
                        .map(GrantedAuthority::getAuthority)
                        .collect(Collectors.toList()));
        return generateToken(username, claims);
    }

    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    private static String generateToken(String subject, Map<String, Object> claims) {
        Date expirationDate = new Date(System.currentTimeMillis() + JwtConstants.EXPIRATION);
        return JwtConstants.TOKEN_PREFIX + Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS512, JwtConstants.JWT_SECRET_KEY)
                .compact();
    }

    /**
     * 从令牌中获取用户名
     *
     * @param token 令牌
     * @return 用户名
     */
    public static String getUsernameFromToken(String token) {
        String username;
        try {
            Claims claims = getClaimsFromToken(token);
            username = claims.getSubject();
        } catch (Exception e) {
            username = null;
        }
        return username;
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    public static Claims getClaimsFromToken(String token) {
        Claims claims;
        try {
            claims = Jwts.parser()
                    .setSigningKey(JwtConstants.JWT_SECRET_KEY)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            claims = null;
        }
        return claims;
    }

    /**
     * 验证令牌
     *
     * @param token
     * @param username
     * @return
     */
    public static Boolean validateToken(String token, String username) {
        String name = getUsernameFromToken(token);
        return (Objects.equals(username, name) && !isTokenExpired(token));
    }

    /**
     * 判断令牌是否过期
     *
     * @param token 令牌
     * @return 是否过期
     */
    public static Boolean isTokenExpired(String token) {
        try {
            Claims claims = getClaimsFromToken(token);
            Date expiration = claims.getExpiration();
            return expiration.before(new Date());
        } catch (Exception e) {
            return false;
        }
    }
}